/*
 * @Author: Zhang Wei
 * @Date: 2024-05-27 22:19:34
 * @LastEditors: Zhang Wei
 * @LastEditTime: 2024-05-27 22:38:26
 * @FilePath: \schulte-meter\miniprogram\utils\GameRecord\GameRecord.ts
 * @Description: 
 * @Word: There is nothing either good or bad, but thinking makes it so.
 */
import { getUserInfo } from "../util"
import { saveGameRecord } from "../../api/game-record.js"

/** 游戏记录模块 */
export class GameRecord {

  LOCAL_STORAGE_KEY = "gameRecord";

  /** 构造函数 */
  // constructor() { }

  /** 获取数据 */
  getData() {
    return this.getDataLocal()
  }

  /** 从本地获取数据 */
  getDataLocal(): null | IGameRecordItem[] {
    const data = wx.getStorageSync(this.LOCAL_STORAGE_KEY);
    if (!data || data === '') return null
    return data;
  }

  /** 将数据存入本地 */
  saveDataLocal(data: IGameRecordItem[]) {
    wx.setStorageSync(this.LOCAL_STORAGE_KEY, data);
  }

  /** 保存一条游戏记录 */
  saveDataNew(newOneData: IGameRecordItem) {

    if (!newOneData) return false

    // 优先存入本地
    this.saveDataNew2Local(newOneData)

    const requestData = Object.assign({}, newOneData, {
      gameDate: newOneData.gameDateStr,
      userId: getUserInfo().userId,
    })

    if (!requestData.gameDateStr) delete requestData.gameDateStr

    saveGameRecord(requestData).then((res: any) => {
      if (!res || !res.ok) return false
    })
  }

  /** 保存一条新数据到本地 */
  saveDataNew2Local(newOneData: IGameRecordItem) {
    let localList = this.getDataLocal() || [];

    localList.push(newOneData);

    this.saveDataLocal(localList);
  }

  /** 获取最佳得分 */
  getBaseGameRecord() {
    const list = this.getData() || []

    if (!list.length) return null

    return list.reduce((prev, curr) => {
      return prev.score > curr.score ? prev : curr
    });
  }

  /** 从接口获取数据
   *  TODO: 接口对接
   */
  getDataFetch() { }
}
